<template>
  <div class="messageGroupTree">
    <t-space direction="vertical" style="width: 100%">
      <t-popconfirm content="确认要引入部门数据吗？引入后会覆盖原数据，请谨慎操作！" @confirm="handleImportDeptData">
        <t-button block theme="warning">引入部门数据</t-button>
      </t-popconfirm>
      <t-tree
        :data="messageGroupTree"
        activable
        expand-all
        height="calc(100vh - 284px)"
        hover
        :actived="selectedId ? [selectedId] : []"
        :keys="{ label: 'name', value: 'id' }"
        @active="handleActive"
      >
        <template #operations="{ node }">
          <t-space>
            <t-icon name="add" v-if="node.data.deptId" @click="handleOpenDialog('create', { parentId: node.data.deptId })" />
            <t-icon name="edit" @click="handleOpenDialog('update', { id: node.data.id })" />
            <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: node.data.id })">
              <t-icon name="delete" />
            </t-popconfirm>
          </t-space>
        </template>
      </t-tree>
    </t-space>
    <!-- 自定义对话框 -->
    <custom-dialog
      ref="customDialogRef"
      v-slot="{ formData, readonly }"
      :api-map="messageGroupCRUD"
      header="*组"
      @request-success="handleDialogRequestSuccess"
    >
      <t-form-item label="父级部门" name="parentId" :rules="[{ required: true, message: '请选择父级部门' }]">
        <t-cascader
          v-model:value="formData.parentId"
          :options="messageGroupTree"
          :keys="{ value: 'deptId', label: 'name' }"
          placeholder="请选择父级部门"
          filterable
          clearable
          check-strictly
          disabled
        />
      </t-form-item>
      <!-- <t-form-item label="部门名称" name="deptId" :rules="[{ required: true, message: '请选择部门名称' }]">
        <t-cascader
          v-model:value="formData.deptId"
          :options="messageGroupTree"
          :keys="{ value: 'deptId', label: 'name' }"
          placeholder="请选择部门名称"
          filterable
          clearable
          :readonly="readonly"
          check-strictly
          @change="
            (value, context) => {
              if (value) {
                const parentId = context.node.data.parentId;
                formData.parentId = parentId;
              } else {
                formData.parentId = undefined;
              }
            }
          "
        />
      </t-form-item> -->
      <t-form-item label="组名称" name="name" :rules="[{ required: true, message: '请输入组名称' }]">
        <t-input v-model:value="formData.name" placeholder="请输入组名称" clearable :readonly="readonly" />
      </t-form-item>
      <t-form-item label="显示顺序" name="sort" :rules="[{ required: true, message: '请输入显示顺序' }]">
        <t-input-number
          v-model:value="formData.sort"
          :decimal-places="0"
          min="0"
          :allow-input-over-limit="false"
          placeholder="请输入显示顺序"
          clearable
          :readonly="readonly"
          style="width: 100%"
        />
      </t-form-item>
    </custom-dialog>
  </div>
</template>

<script setup lang="ts">
import { MessagePlugin, TreeNodeValue } from 'tdesign-vue-next';
import { ref, useTemplateRef } from 'vue';

import { importDeptData, messageGroupCRUD } from '@/api/config/message-group';
import CustomDialog from '@/components/custom/dialog/index.vue';
import listToTree from '@/utils/listToTree';

// 选择的ID
const selectedId = defineModel<number>('selectedId');
// 消息组列表
const messageGroupList = ref([]);
// 消息组树
const messageGroupTree = ref([]);
// 处理获取消息组
const handleGetMessageGroup = () => {
  const params = {
    pageSize: -1,
  };
  messageGroupCRUD.page(params).then((data) => {
    messageGroupList.value = data.list;
    messageGroupTree.value = listToTree(data.list, 'deptId');
  });
};
handleGetMessageGroup();
// 处理引入部门树
const handleImportDeptData = () => {
  importDeptData({})
    .then(() => {
      MessagePlugin.success('引入成功');
      handleGetMessageGroup();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理激活
const handleActive = (value: TreeNodeValue[]) => {
  selectedId.value = value[0] as number;
};
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleGetMessageGroup();
  if (result.mode === 'update') handleGetMessageGroup();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  messageGroupCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleGetMessageGroup();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};

defineExpose({
  messageGroupList,
  messageGroupTree,
});
</script>

<style lang="less" scoped>
.messageGroupTree {
  padding-right: 16px;
  margin-right: 16px;
  border-right: 1px solid var(--td-border-level-1-color);
}
</style>
